//
//  SettingsTableViewController.m
//  ITHome
//
//  Created by lanou3g on 15/7/14.
//  Copyright (c) 2015年 YAX. All rights reserved.
//

#import "SettingsTableViewController.h"
#import "SettingsTableViewCell.h" //设置自定cell
#import "FeedBackTableViewController.h" //给IT家园提意见
#import "AboutViewController.h" // 关于IT家园
#import "CacheSizeModel.h"
#import "FontViewController.h"  //字体选中控制器
#import <TencentOpenAPI/TencentOAuth.h>
#import "UserInfoModel.h"
#import "LoginViewController.h"


@interface SettingsTableViewController ()<UIAlertViewDelegate>
{
   __block NSString *cacheSize;
    float fontsize;
}

@property (nonatomic, strong) NSArray *permissions; // 权限
@property(nonatomic,strong)NSUserDefaults *user;

@end

@implementation SettingsTableViewController
- (instancetype)initWithNibName:(NSString *)nibNameOrNil bundle:(NSBundle *)nibBundleOrNil
{
    self = [super initWithNibName:nibNameOrNil bundle:nibBundleOrNil];
    if (self) {
         self.tableView = [[UITableView alloc] initWithFrame:self.view.bounds style: UITableViewStyleGrouped];
    }
    return self;
}

#pragma mark - 初始化第三方登陆的权限
- (instancetype)init
{
    self = [super init];
    if (self) {
        self.permissions = [NSArray arrayWithObjects:@"get_user_info",@"get_simple_userinfo", @"add_t", nil];
    }
    return self;
}


- (void)viewDidLoad
{
    [super viewDidLoad];
   

    // 监听登录成功的广播
    [[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(refresh) name:kLoginSuccessed object:nil];
    [self loadNavigationIndfo];

}


#pragma mark - 修改导航栏颜色
- (void)viewWillAppear:(BOOL)animated
{
    self.navigationController.navigationBar.barTintColor = [UIColor RGBColor:71 green:128 blue:208 alpha:1];
}

#pragma mark - 通知的方法
- (void)refresh
{
    [self.tableView reloadData];
}

#pragma mark - 设置导航栏
- (void)loadNavigationIndfo
{
     // 导航栏颜色
    self.navigationController.navigationBar.barTintColor = [UIColor redColor];
    
    self.navigationItem.title = @"设置";
    // 取消
    UIBarButtonItem *leftBackButton = [UIBarButtonItem itemWithTarget:self Action:@selector(backAction) image:@"home_back" highImage:@"home_back_highlighted"];
    self.navigationItem.leftBarButtonItem = leftBackButton;
    
    // 标题
    [[UINavigationBar appearance] setTitleTextAttributes:@{NSForegroundColorAttributeName:[UIColor whiteColor]}];
    
}

#pragma mark - 返回按钮触发事件
- (void)backAction
{
    [self dismissViewControllerAnimated:YES completion:nil];
}

#pragma mark - Table view data source
- (NSInteger)numberOfSectionsInTableView:(UITableView *)tableView
{
    return 3;
}

- (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section
{
    NSInteger row = 0;
    switch (section) {
        case 0:
            row = 2;
            break;
        case 1:
            row = 4;
            break;
        case 2:
            row = 3;
            break;
        default:
            break;
    }
    return row;
}

- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath
{
    static NSString *cellIdentifier = @"cell";
    UITableViewCell *cell = [tableView dequeueReusableCellWithIdentifier:cellIdentifier];
    if (cell == nil)
    {
        cell = [[UITableViewCell alloc] initWithStyle:UITableViewCellStyleValue1 reuseIdentifier:cellIdentifier];
    }
    
    switch (indexPath.section)
    {
        case 0:
        {
            switch (indexPath.row)
            {
                case 0:
                {
                    // 判断登陆状态
                    // 先取出登陆状态
                    NSString *loginStatus = [[NSUserDefaults standardUserDefaults] stringForKey:kLoginStatus];
                    if ([loginStatus isEqualToString:@"YES"])
                    {
                        // 从数据库取出数据
                        NSMutableArray *userInfoArray = [FMDBManage selectAllUserInfo];
                        UserInfoModel *userInfoModel = [userInfoArray objectAtIndex:0];
                        cell.textLabel.text = userInfoModel.nickname;
                        // 从数据库取出数据
                        cell.detailTextLabel.text = @"退出登录";
                        cell.imageView.image = [UIImage imageNamed:@"setting_personal"];
                    }
                    else
                    {
                        cell.textLabel.text = @"访客";
                        cell.detailTextLabel.text = @"点击登录";
                        cell.imageView.image = [UIImage imageNamed:@"setting_personal"];
                    }
                }
                    break;
                case 1:
                {
                    //开启线程为cell赋值缓存大小。
                    cell.detailTextLabel.text = @"0.00M";
                    dispatch_async( dispatch_get_global_queue(DISPATCH_QUEUE_PRIORITY_DEFAULT, 0), ^{
                        // 执⾏耗时的异步操作...
                        CacheSizeModel *ch = [CacheSizeModel shareInstance];
                         float cacheSize1 = [ch checkTmpSize];
                        YAXLog(@"%f",cacheSize1);
                        dispatch_async(dispatch_get_main_queue(), ^{
        
                            // 回到主线程,执⾏UI刷新操作
                            cell.detailTextLabel.text = [NSString stringWithFormat:@"%0.2fM",cacheSize1];
                            //记录下内存大小，弹框用到
                            cacheSize = cell.detailTextLabel.text;
                        });
                    });

                    cell.textLabel.text = @"清理缓存";
                    

                    cell.imageView.image = [UIImage imageNamed:@"setting_cache"];
                    break;                }
                    break;
                default:
                    break;
            }
            break;
        }
        case 1:
        {
            if (indexPath.row == 0)
            {
                cell.textLabel.text = @"字体选择";
                
                NSUserDefaults *font = [NSUserDefaults standardUserDefaults];
                CGFloat f = [font floatForKey:@"fontSize"];
                if (f == 0 ) {
                    cell.detailTextLabel.text = [NSString stringWithFormat:@"当前14号字体"];
                }else{
                    cell.detailTextLabel.text = [NSString stringWithFormat:@"当前%d号字体",(int)f];
                }
                cell.imageView.image = [UIImage imageNamed:@"setting_font"];
            }
            else
            {
                static NSString *settingsCellIdentifier = @"settingsCell";
                [tableView registerClass:[SettingsTableViewCell class] forCellReuseIdentifier:settingsCellIdentifier];
                SettingsTableViewCell *settingCell = [tableView dequeueReusableCellWithIdentifier:settingsCellIdentifier];
                switch (indexPath.row)
                {
                    case 1:
                    {
                        settingCell.textInfoLabel.text = @"2G/3G下无图模式";
                        settingCell.iconImageView.image = [UIImage imageNamed:@"setting_traffic"];
                        BOOL b = [[NSUserDefaults standardUserDefaults]boolForKey:@"isPicture"];
                        [settingCell.settingsSwith addTarget:self action:@selector(noPictureMode:) forControlEvents:UIControlEventValueChanged];
                        [settingCell.settingsSwith setOn:b];
                        break;
                    }
                    case 2:
                        settingCell.textInfoLabel.text = @"通知推送";
                        settingCell.iconImageView.image = [UIImage imageNamed:@"setting_push"];
                        break;
                    case 3:
                        settingCell.textInfoLabel.text = @"夜间模式";
                        settingCell.iconImageView.image = [UIImage imageNamed:@"setting_night"];
                        BOOL b = [[NSUserDefaults standardUserDefaults] boolForKey:@"isNight"];
                        [settingCell.settingsSwith setOn:b];
                        [settingCell.settingsSwith addTarget:self action:@selector(NightMode:) forControlEvents:UIControlEventValueChanged];
                        break;
                    default:
                        break;
                }
                return settingCell;
            }
            break;
        }
        case 2:
        {
            switch (indexPath.row)
            {
                case 0:
                    cell.textLabel.text = @"给IT家园提意见";
                    cell.imageView.image = [UIImage imageNamed:@"setting_feedback"];
                    break;
                case 1:
                    cell.textLabel.text = @"检查更新";
                    cell.imageView.image = [UIImage imageNamed:@"setting_update"];
                    break;
                case 2:
                    cell.textLabel.text = @"关于IT家园";
                    cell.imageView.image = [UIImage imageNamed:@"setting_about"];
                    break;
                default:
                    break;
            }
            break;
        }
            
        default:
            break;
    }
    
    cell.textLabel.font = [UIFont systemFontOfSize:15];
    cell.detailTextLabel.textColor = [UIColor orangeColor];
    cell.detailTextLabel.font = [UIFont systemFontOfSize:14];
    
    // 设置辅助样式
    if (indexPath.section == 0 || indexPath.section == 1)
    {
        if (indexPath.row == 0)
        {
            cell.accessoryType = UITableViewCellAccessoryDisclosureIndicator;
        }
    }
    
    if (indexPath.section == 2)
    {
        cell.accessoryType = UITableViewCellAccessoryDisclosureIndicator;
    }
    
    return cell;
}

#pragma mark - 无图模式
- (void)noPictureMode:(UISwitch *)sender
{
    if ([sender isOn])
    {
        [[NSUserDefaults standardUserDefaults] setBool:YES forKey:@"isPicture"];
    }
    else
    {
        [[NSUserDefaults standardUserDefaults] setBool:NO forKey:@"isPicture"];
    }
}


#pragma mark - 切换白天 夜间模式
- (void)NightMode:(UISwitch *)sender
{
    if ([sender isOn])
    {
        self.user = [NSUserDefaults standardUserDefaults];
        [self.user setBool:YES forKey:@"isNight"];
        [self.user setBool:YES forKey:@"isOn"];
        [self.user synchronize];
        self.view.window.alpha = 0.4;
    }
    else
    {
        self.user = [NSUserDefaults standardUserDefaults];
        [self.user setBool:NO forKey:@"isNight"];
        [self.user setBool:NO forKey:@"isOn"];
        self.view.window.alpha = 1;
    }
    
}

- (CGFloat)tableView:(UITableView *)tableView heightForFooterInSection:(NSInteger)section
{
    return 1;
}

- (CGFloat)tableView:(UITableView *)tableView heightForHeaderInSection:(NSInteger)section
{
    return 10;
}

#pragma mark - 点击cell的触发事件
- (void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath
{
    // 取消点击效果
    [tableView deselectRowAtIndexPath:indexPath animated:YES];
    switch (indexPath.section)
    {
        case 0:
        {
            switch (indexPath.row)
            {
                case 0:
                {
                    // 判断登陆状态
                    // 先取出登陆状态
                    NSString *loginStatus = [[NSUserDefaults standardUserDefaults] stringForKey:kLoginStatus];
                    if ([loginStatus isEqualToString:@"YES"])
                    {
                        // 提示用户要不要退出
                        UIAlertView *alertView = [[UIAlertView alloc] initWithTitle:nil message:@"退出登录？" delegate:self cancelButtonTitle:@"取消" otherButtonTitles:@"退出", nil];
                        alertView.delegate = self;
                        alertView.tag = 200;
                        [alertView show];
                    }
                    else
                    {
                        // 跳转到登陆页面
                        LoginViewController *loginViewVc = [[LoginViewController alloc] init];
                        UINavigationController *nav = [[UINavigationController alloc] initWithRootViewController:loginViewVc];
                        nav.modalTransitionStyle = UIModalTransitionStyleCoverVertical;
                        [self presentViewController:nav animated:YES completion:nil];
                    }

                    break;
                }
                case 1:
                {
                    ;
                    UIAlertView *cache = [[UIAlertView alloc] initWithTitle:@"提示" message:[NSString stringWithFormat:@"缓存大小为%@.确认要清理缓存吗？",cacheSize] delegate:self cancelButtonTitle:@"取消" otherButtonTitles:@"确定", nil];
                    cache.delegate = self;
                    cache.tag = 100;
                    [cache show];
                    break;
                }
                default:
                    break;
            }
            break;
        }
        case 1:
        {
            if (indexPath.row == 0)
            {
//                [ProgressHUD progressHUD:self.view labelText:@"字体选择"];
                FontViewController *fontVc = [[FontViewController alloc] init];
                fontVc.block = ^(float f){
                    fontsize = f;
                    [self.tableView reloadData];
                };
                [self presentViewController:fontVc animated:YES completion:nil];
                break;
            }else
            {
                break;
            }
        }
        case 2:
        {
            switch (indexPath.row)
            {
                case 0:
                {
                    FeedBackTableViewController *feedBackVc = [[FeedBackTableViewController alloc] init];
                    UINavigationController *nav = [[UINavigationController alloc] initWithRootViewController:feedBackVc];
                    nav.modalTransitionStyle = UIModalTransitionStyleCrossDissolve;
                    [self presentViewController:nav animated:YES completion:nil];
                    
                    break;
                }
                case 1:
                {
                    [ProgressHUD progressHUD:self.view labelText:@"当前已是最新版本"];
                    break;
                }
                case 2:
                {
                    AboutViewController *aboutVc = [[AboutViewController alloc] init];
                    UINavigationController *nav = [[UINavigationController alloc] initWithRootViewController:aboutVc];
                    nav.modalTransitionStyle = UIModalTransitionStyleCrossDissolve;
                    [self presentViewController:nav animated:YES completion:nil];
                    break;
                }
                default:
                    break;
            }
            break;
        }
            
        default:
            break;
    }
}

#pragma - mark - UIAlerView 代理方法
- (void)alertView:(UIAlertView *)alertView clickedButtonAtIndex:(NSInteger)buttonIndex
{
    if (alertView.tag == 100)
    {
        if (buttonIndex == 1)
        {
            //值清理图片.
//            CacheSizeModel * cache = [CacheSizeModel shareInstance];
//            [cache clearTmpPics];
            //清理cache文件夹.
            [CacheSizeModel clearCache];
            [ProgressHUD progressHUD:self.view labelText:@"清理完成"];
            [self.tableView reloadData];
        }
    }
    else if (alertView.tag == 200)
    {
        if (buttonIndex == 0)
        {
//            YAXLog(@"取消");
        }
        else
        {
            // 删除所有所用信息
            [FMDBManage deleteAllUserInfo];
            
            // 改变登陆状态
            NSUserDefaults *userDefaults = [NSUserDefaults standardUserDefaults];
            [userDefaults setObject:@"NO" forKey:kLoginStatus];
            
            // 刷新表格
            [self.tableView reloadData];
            
            // 创建一个通知··用户退出状态的通知 让相关页面刷新数据
            [[NSNotificationCenter defaultCenter] postNotificationName:kexitSuccessed object:self];

        }
    }
}


#pragma mark - 内容警告触发方法
- (void)didReceiveMemoryWarning
{
    [super didReceiveMemoryWarning];
    [[SDImageCache sharedImageCache] clearMemory];
}

@end
